package com.spt.security.dao;

import java.util.List;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Maps;
import com.spt.fjj.service.models.common.AnnotationCommonService;
@Service
public class ShiroUserImpl extends AnnotationCommonService implements IShiroUser {
    private static Logger log = LogManager.getLogger("com.spt.ws.man");
    @Override
    public Map<String, Object> getByUsername(String userName) {
        Map<String, Object> user = Maps.newHashMap();
       /* Map<String, Object> role = Maps.newHashMap();
        Map<String, String> permission = Maps.newHashMap();
        List<Map<String,String>> permissions = Lists.newArrayList();
        List<Map<String,Object>> roles = Lists.newArrayList();
        permission.put("PERMISSION", "admin:manage");
        permissions.add(permission);
        role.put("NAME", "ADMIN");
        role.put("Permissions", permissions);
        roles.add(role);
        user.put("ROLES", roles);
        user.put("USERNAME", "admin");
        user.put("PASSWD", "123");
        user.put("NICKNAME", "AD");*/
        try {
            List<Map<String, Object>> liuser = this._queryMultex("select * from t_shiro_user where username=?",userName);
            if(liuser == null || liuser.size() == 0) return null;
            user = liuser.get(0);
            List<Map<String,Object>> roles = this._queryMultex("select user_id,role_id,rolename name from t_shiro_user_role ur left join t_shiro_role r on r.id = ur.role_id where ur.user_id = ?",user.get("ID"));
            for(Map<String, Object> role : roles) {
                List<Map<String, Object>> permissions = this._queryMultex("select permission from t_shiro_role_permission rp left join t_shiro_permission p on p.id = rp.permission_id where rp.role_id = ?", role.get("ID"));
                role.put("Permissions", permissions);
            }
            user.put("ROLES", roles);
            return user;
        }catch (Exception e) {
            log.error("取用户信息出错，错误信息：" + e.getMessage());
            throw new RuntimeException("取用户信息出错，错误信息：" + e.getMessage());
        }
    }

    @Override
    public String encryptPasswd(String passwd,String userName) {
        String hashAlgorithmName = "MD5";
        if(passwd == null) return null;
        //String credentials = "111111";
        int hashIterations = 1024;
        ByteSource credentialsSalt = ByteSource.Util.bytes(userName);
        Object obj = new SimpleHash(hashAlgorithmName, passwd, credentialsSalt, hashIterations);
        return (String) obj.toString();
    }

    @Override
    public List<Map<String, Object>> getUsers() {
        String sql = "select username ,nickname ,describe ,id,createdt,creator,lastupdate,"
                + "(select  to_char(wm_concat(rolename )) from t_shiro_role where id in (select role_id  from t_shiro_user_role where user_id=u.id)) roles,"
                + "(select  to_char(wm_concat(id ))  from t_shiro_role where id in (select role_id  from t_shiro_user_role where user_id=u.id)) roleid "
                + "from T_SHIRO_USER u";
        try{
            return this._queryMultex(sql);
        }catch (Exception e) {
            log.error("取用户信息出错，错误信息：" + e.getMessage());
            throw new RuntimeException("取用户信息出错，错误信息：" + e.getMessage());
        }
    }

    @Transactional
    @Override
    public Map<String, Object> addUser(Map<String, String> param) throws Exception {
        try {
            String checkSql = "select count(*) from t_shiro_user where username = ?";
            String count = this._querySingle(checkSql,param.get("USERNAME"));
            if(!"0".equals(count)) throw new Exception("用户名：" + param.get("USERNAME") + " 已有人使用！");
            String userId = this._querySingle("select SEQ_SECURITY.nextval from dual");
            String insSql = "insert into t_shiro_user (id,username,nickname,passwd,describe,createdt,creator,lastupdate) values(?,?,?,?,?,sysdate,?,sysdate)";
            String newEncypt = this.encryptPasswd("111111", param.get("USERNAME"));
            this._update(insSql, userId,param.get("USERNAME"),param.get("NICKNAME"),newEncypt,param.get("DESCRIBE"),param.get("creator"));
            String roles = param.get("ROLEID");
            if(roles != null) {
                String setRoleSql = "insert into T_SHIRO_USER_ROLE (user_id, role_id, createdt,creator) values(?,?,sysdate,?)";
                String[] roleArray = roles.split(",");
                for(String roleid : roleArray) {
                    this._update(setRoleSql,userId, roleid, param.get("creator"));
                }
            }
            String sql = "select username ,nickname ,describe ,id,createdt,creator,lastupdate,"
                    + "(select  to_char(wm_concat(rolename )) from t_shiro_role where id in (select role_id  from t_shiro_user_role where user_id=u.id)) roles,"
                    + "(select  to_char(wm_concat(id ))  from t_shiro_role where id in (select role_id  from t_shiro_user_role where user_id=u.id)) roleid "
                    + "from T_SHIRO_USER u where u.id = ?";
            return this._queryMultex(sql, userId).get(0);
        }catch (Exception e) {
            log.error("增加用户信息出错，错误信息：" + e.getMessage());
            throw new RuntimeException("增加用户信息出错，错误信息：" + e.getMessage());
        }
    }

    @Transactional
    @Override
    public void delUser(String userId) throws Exception {
        String sql1 = "delete from t_shiro_user where id = ? ";
        String sql2 = "delete from T_SHIRO_USER_ROLE where user_id = ?";
        try{
            this._update(sql1,userId);
            this._update(sql2,userId);
        }catch (Exception e) {
            log.error("删除用户信息出错，错误信息：" + e.getMessage());
            throw new RuntimeException("删除用户信息出错，错误信息：" + e.getMessage());
        }
        
        
    }

    @Override
    public void modifyPasswd(String oldPasswd, String newPasswd, String userName) throws Exception {
        try {
            String old = this.encryptPasswd(oldPasswd, userName);
            String checkSql = "select count(*) from t_shiro_user where username = ? and passwd = ?";
            String count = this._querySingle(checkSql,userName, old);
            if(!"1".equals(count)) throw new Exception("原密码错误！");
            String newEncypt = this.encryptPasswd(newPasswd, userName);
            String update = "update t_shiro_user set passwd = ?,lastupdate=sysdate where userName=?";
            this._update(update, newEncypt, userName);
        }catch (Exception e) {
            log.error("修改用户密码出错，错误信息：" + e.getMessage());
            throw new RuntimeException("修改用户密码出错，错误信息：" + e.getMessage());
        }
    }

    @Override
    public void resetPasswd(String userName) {
        String newEncypt = this.encryptPasswd("111111", userName);
        String update = "update t_shiro_user set passwd = ?,lastupdate=sysdate where userName=?";
        try{
            this._update(update, newEncypt, userName);
        }catch (Exception e) {
            log.error("重置用户密码出错，错误信息：" + e.getMessage());
            throw new RuntimeException("重置用户密码出错，错误信息：" + e.getMessage());
        }
        
    }


    @Transactional
    @Override
    public Map<String, Object> modifyUserRoles(Map<String, String> param) {
        try {
            String del = "delete from T_SHIRO_USER_ROLE where user_id = ?";
            String update = "update t_shiro_user set describe = ?,nickname=?,lastupdate=sysdate where id = ?";
            this._update(update, param.get("DESCRIBE"), param.get("NICKNAME"), param.get("ID"));
            this._update(del,param.get("ID"));
            String roles = param.get("ROLEID");
            if(roles != null) {
                String setRoleSql = "insert into T_SHIRO_USER_ROLE (user_id, role_id, createdt,creator) values(?,?,sysdate,?)";
                String[] roleArray = roles.split(",");
                for(String roleid : roleArray) {
                    this._update(setRoleSql,param.get("ID"), roleid, param.get("creator"));
                }
            }
            String sql = "select username ,nickname ,describe ,id,createdt,creator,lastupdate,"
                    + "(select  to_char(wm_concat(rolename )) from t_shiro_role where id in (select role_id  from t_shiro_user_role where user_id=u.id)) roles,"
                    + "(select  to_char(wm_concat(id ))  from t_shiro_role where id in (select role_id  from t_shiro_user_role where user_id=u.id)) roleid "
                    + "from T_SHIRO_USER u where u.id = ?";
            return this._queryMultex(sql, param.get("ID")).get(0);
        }catch (Exception e) {
            log.error("修改用户信息出错，错误信息：" + e.getMessage());
            throw new RuntimeException("修改用户信息出错，错误信息：" + e.getMessage());
        }
    }

}
